#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Author:Lijiacai
Email:1050518702@qq.com
===========================================
CopyRight@JackLee.com
===========================================
"""

import os
import sys
import json
from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.clock import Clock
from kivy.lang import Builder
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.core.window import Window
import requests
import pandas
import datetime
from lxml.etree import HTML


class Spider():
    def get_Cookie(self):
        return "JSESSIONID=BA4D0A868E24CFD9DDFB6779A86F8F8A-n1; acw_tc=7b39758515954723913517329ec99562d988ce73fedc8db57dbb30290fcf36"

    def get(self, max_page=1, Cookie=""):
        url = "https://manage.feezu.cn/manage/car/teleControl/init?start={}"

        if not Cookie:
            Cookie = self.get_Cookie()
        headers = {
            "Cookie": Cookie,
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36"
        }
        res = []
        for i in range(max_page + 1):
            url_ = url.format(i * 20)
            data = self.get_data(url_, headers=headers)
            res += self.parse_data(data)

        res = pandas.DataFrame(res, columns=["当前网点", "车牌号", "车型", "设备号", "状态", "更新时间"])
        now = datetime.datetime.now().date()
        try:
            os.mkdir("data")
        except:
            pass
        res.to_excel("./data/" + str(now) + ".xlsx", encoding="utf8")

    def get_data(self, url, **kwargs):
        return requests.get(url, **kwargs).text

    def parse_data(self, html):
        html = HTML(html)
        trs = html.xpath("//table/tbody/tr")
        res = []
        for tr in trs:
            t0 = tr.xpath("./td")[0].text
            t1 = tr.xpath("./td")[1].text
            t2 = tr.xpath("./td")[2].text
            t3 = tr.xpath("./td")[3].text
            t4 = tr.xpath("./td")[4].text
            t5 = tr.xpath("./td")[5].text
            if t0 != None:
                t0 = t0.strip()
            if t1 != None:
                t1 = t1.strip()
            if t2 != None:
                t2 = t2.strip()
            if t0 != None:
                t3 = t3.strip()
            if t4 != None:
                t4 = t4.strip()
            if t5 != None:
                t5 = t5.strip()
            res.append([t0, t1, t2, t3, t4, t5])

        return res


class Index(Widget):

    def black(self):
        pass

    def btn_release(self):
        Cookie = self.ids["Cookie"].text
        MaxPage = self.ids["MaxPage"].text
        try:
            MaxPage = int(MaxPage) + 1
        except:
            MaxPage = 1
        Spider().get(max_page=MaxPage, Cookie=Cookie)
        return True


class SpiderApp(App):
    pass

    # def __init__(self, **kwargs):
    #     super(SpiderApp, self).__init__(**kwargs)
    #     from kivy.base import EventLoop
    #     EventLoop.window.bind(on_keyboard=self.hook_keyboard)
    #
    #     Clock.schedule_interval(self.redraw, 1.0 / 30.0)
    #
    # def redraw(self, *args, **kwargs):
    #     pass
    #
    # def hook_keyboard(self, window, keycode, *args):
    #     key = {
    #         119: 119,
    #         115: 115,
    #         97: 97,
    #         100: 100
    #     }
    #
    #     return True


if __name__ == '__main__':
    Window.size = (600, 400)
    SpiderApp().run()
